﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MsgCenter.DAL.Base;
using Utility;
using Utility.Json;
using Utility.Comm;
using Utility.Model;
using Hxj.Data;
using System.Data;

namespace MsgCenter.BLL.Impl
{
    public class BLL_SysGroup
    {
        private readonly BaseService dal = new BaseService();
        public DataTable GetGroupList(WhereClip wcp)
        {
            using (DataTable dt = dal.GetDataBase().From<Sys_Group>() //选择表 
                                              .Select(Sys_Group._.All)  //设置选择的字段数目 
                                              .Where(wcp)   //条件 
                                              .ToDataTable())   //返回datatable
            {
                SetGroupUser(dt);
                return dt;
            }
        }
        public JsonJqGridData GetGroupList(PagerCondition pager)
        {
            try
            {
                pager.RecordCount = dal.GetDataBase().From<Sys_Group>()
                                                          .Where(pager.ComplexSearchCondition)
                                                          .Count();

                #region 固定写法，判断当前页面对象删除后，当前页和最大页之间的关系
                if (pager.CurrentPage > pager.PageCount)
                    pager.CurrentPage = pager.PageCount;
                #endregion

                if (pager.OrderBy == null)
                    pager.OrderBy = new OrderByClip(Sys_Group._.CreateDate, OrderByOperater.DESC);

                using (DataTable dt = dal.GetDataBase().From<Sys_Group>() //选择表 
                                             .Select(Sys_Group._.All)  //设置选择的字段数目
                                             .Page(pager.PageSize, pager.CurrentPage)  //分页显示
                                             .Where(pager.ComplexSearchCondition)   //条件
                                             .OrderBy(pager.OrderBy)   //排序
                                             .ToDataTable())   //返回datatable
                {
                    SetGroupUser(dt);
                    JsonJqGridData grid = new JsonJqGridData();
                    grid.page = pager.CurrentPage;
                    grid.rows = dt;
                    grid.records = pager.RecordCount;
                    grid.total = pager.PageCount;
                    return grid;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public Dictionary<string, string> GetGroupUserDic(string strGroupID)
        {
            Dictionary<string, string> dicList = new Dictionary<string, string>();
            using (IDataReader dr = dal.GetDataBase().From<Sys_User>().LeftJoin<Sys_GroupUser>(Sys_User._.UserID == Sys_GroupUser._.UserID)
                 .Select(Sys_User._.Name, Sys_User._.UserID)
                 .Where(Sys_GroupUser._.GroupID == strGroupID).ToDataReader())
            {
                while (dr.Read())
                {
                    dicList.Add(dr["UserID"].ToString(), dr["Name"].ToString());
                }
                dr.Close();
                dr.Dispose();
            }
            return dicList;
        }


        private void SetGroupUser(DataTable dt)
        {
            DataColumn dtColumn = new DataColumn();
            dtColumn.ColumnName = "UserName";
            dt.Columns.Add(dtColumn);
            dtColumn = new DataColumn();
            dtColumn.ColumnName = "UserID";
            dt.Columns.Add(dtColumn);
            Dictionary<string, string> dicUserRole = null;
            string strUserRole = string.Empty;
            string strUserRoleID = string.Empty;
            foreach (DataRow drUser in dt.Rows)
            {
                strUserRole = string.Empty;
                strUserRoleID = string.Empty;
                dicUserRole = GetGroupUserDic(drUser["GroupID"].ToSafeString());
                if (dicUserRole.Count > 0)
                {
                    foreach (KeyValuePair<string, string> item in dicUserRole)
                    {
                        if (strUserRole.Length == 0)
                        {
                            strUserRole = item.Value;
                            strUserRoleID = item.Key;
                        }
                        else
                        {
                            strUserRole += "," + item.Value;
                            strUserRoleID += "," + item.Key;
                        }
                    }
                }
                drUser["UserName"] = strUserRole;
                drUser["UserID"] = strUserRoleID;
            }
        }
        /// <summary>
        /// 保存 
        /// </summary>
        /// <param name="model">用户实体</param>
        /// <param name="list">用户对应的角色列表</param>
        public void Save(Sys_Group model, List<Sys_GroupUser> list)
        {
            DbTrans trans = dal.GetDataBase().BeginTransaction();
            try
            {
                dal.Save<Sys_Group>(model, trans);
                if (list != null && list.Count > 0)
                {
                    dal.ExecuteNonQuery("delete Sys_GroupUser where GroupID='" + model.GroupID + "'");
                    if (list != null)
                    {
                        foreach (Sys_GroupUser modelRoles in list)
                        {
                            dal.Save<Sys_GroupUser>(modelRoles, trans);
                        }
                    }
                }
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw ex;
            }
            finally
            {
                trans.Close();
            }
        }
        /// <summary>
        /// 删除 
        /// </summary>
        /// <param name="strDataID"></param>
        public void Delete(string strDataID)
        {
            if (strDataID.Length > 0)
            {
                string[] idList = strDataID.Trim(',').Split(',');
                DbTrans trans = dal.GetDataBase().BeginTransaction();
                try
                {
                    foreach (string strUserID in idList)
                    {
                        dal.ExecuteNonQuery("Update Sys_Group set Isdelete=1 where GroupID='" + strUserID + "'", trans);
                    }
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    throw ex;
                }
                finally
                {
                    trans.Close();
                }
            }
        }
        /// <summary>
        /// 获取对象实体
        /// </summary>
        /// <param name="wcp"></param>
        /// <returns></returns>
        public Sys_Group GetModel(WhereClip wcp)
        {
            return dal.GetModel<Sys_Group>(wcp);
        }
        /// <summary>
        /// 获取对象实体
        /// </summary>
        /// <param name="wcp"></param>
        /// <returns></returns>
        public Sys_Group GetModel(string id)
        {
            return dal.GetModel<Sys_Group>(Sys_Group._.GroupID == id);
        }
        /// <summary>
        /// 获取分组用户ID
        /// </summary>
        /// <param name="wcp"></param>
        /// <returns></returns>
        public DataTable GetGroupUser(string strGroupID)
        {
            return dal.GetDataBase().From<Sys_GroupUser>()
                .LeftJoin<Sys_User>(Sys_GroupUser._.UserID == Sys_User._.UserID)
                .LeftJoin<Sys_Dept>(Sys_User._.DeptGuID == Sys_Dept._.ID)
                .Select(Sys_GroupUser._.All, Sys_User._.Name, Sys_Dept._.DeptName)
                .Where(Sys_GroupUser._.GroupID == strGroupID).ToDataTable();
        }

        public void SetUserGroup(string strUserIDS, string strGroupID)
        {
            List<string> list = strUserIDS.Split(',').ToList();
            DbTrans trans = dal.GetDataBase().BeginTransaction();
            try
            {
                Sys_GroupUser model = null;
                foreach (string strUserID in list)
                {
                    model = new Sys_GroupUser();
                    model.UserID = strUserID;
                    model.GroupID = strGroupID;
                    dal.Save<Sys_GroupUser>(model, trans);
                }
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw ex;
            }
            finally
            {
                trans.Close();
            }
        }

        public void DeleteGroupUser(string strUserIDS, string strGroupID)
        {
            dal.GetDataBase().Delete<Sys_GroupUser>(Sys_GroupUser._.UserID == strUserIDS && Sys_GroupUser._.GroupID == strGroupID);
        }
    }
}
